<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类别编码" prop="categoryCode">
        <el-input
          v-model="queryParams.categoryCode"
          placeholder="请输入类别编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入类别名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别英文名称" prop="categoryNameEn">
        <el-input
          v-model="queryParams.categoryNameEn"
          placeholder="请输入类别英文名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="祖级列表" prop="ancestorList">
        <el-input
          v-model="queryParams.ancestorList"
          placeholder="请输入祖级列表"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sortNo">
        <el-input
          v-model="queryParams.sortNo"
          placeholder="请输入排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="行状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择行状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_enable_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mdm:materialCategory:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['mdm:materialCategory:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mdm:materialCategory:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="materialCategoryList"
      row-key="tableId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="类别编码" align="center" prop="categoryCode"/>
      <el-table-column label="类别名称" prop="categoryName"/>
      <el-table-column label="类别英文名称" align="center" prop="categoryNameEn"/>
      <el-table-column label="祖级列表" align="center" prop="ancestorList"/>
      <el-table-column label="类别描述" align="center" prop="categoryDesc"/>
      <el-table-column label="父类id" align="center" prop="parentId"/>
      <el-table-column label="排序" align="center" prop="sortNo"/>
      <el-table-column label="行状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_enable_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mdm:materialCategory:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['mdm:materialCategory:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mdm:materialCategory:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改物料类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类别编码" prop="categoryCode">
          <el-input v-model="form.categoryCode" placeholder="请输入类别编码"/>
        </el-form-item>
        <el-form-item label="类别名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入类别名称"/>
        </el-form-item>
        <el-form-item label="类别英文名称" prop="categoryNameEn">
          <el-input v-model="form.categoryNameEn" placeholder="请输入类别英文名称"/>
        </el-form-item>
        <el-form-item label="类别描述" prop="categoryDesc">
          <el-input v-model="form.categoryDesc" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="父类id" prop="parentId">
          <treeselect v-model="form.parentId" :options="materialCategoryOptions" :normalizer="normalizer"
                      placeholder="请选择父类id"/>
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input v-model.number="form.sortNo" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="行状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_enable_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaterialCategory,
  getMaterialCategory,
  delMaterialCategory,
  addMaterialCategory,
  updateMaterialCategory
} from "@/api/mdm/materialCategory";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "MaterialCategory",
  dicts: [ 'sys_enable_status' ],
  components: {
    Treeselect
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 物料类别表格数据
      materialCategoryList: [],
      // 物料类别树选项
      materialCategoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        categoryCode: null,
        categoryName: null,
        categoryNameEn: null,
        ancestorList: null,
        categoryDesc: null,
        parentId: null,
        sortNo: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryCode: [
          { required: true, message: "类别编码不能为空", trigger: "blur" }
        ],
        categoryName: [
          { required: true, message: "类别名称不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父类id不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "行状态不能为空", trigger: "change" }
        ],
        delFlag: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人账号不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "修改人账号不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" }
        ]
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mdm/materialCategory/importData"
      }
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 查询物料类别列表 */
    getList () {
      this.loading = true;
      listMaterialCategory(this.queryParams).then(response => {
        this.materialCategoryList = this.handleTree(response.data, "tableId", "parentId");
        this.loading = false;
      });
    },
    /** 转换物料类别数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.tableId,
        label: node.categoryName,
        children: node.children
      };
    },
    /** 查询物料类别下拉树结构 */
    getTreeselect () {
      listMaterialCategory().then(response => {
        this.materialCategoryOptions = [];
        const data = { tableId: 0, categoryName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "tableId", "parentId");
        this.materialCategoryOptions.push(data);
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        categoryCode: null,
        categoryName: null,
        categoryNameEn: null,
        ancestorList: null,
        categoryDesc: null,
        parentId: null,
        sortNo: 1,
        tableId: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.tableId) {
        this.form.parentId = row.tableId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加物料类别";
    },
    /** 展开/折叠操作 */
    toggleExpandAll () {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getMaterialCategory(row.tableId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料类别";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.tableId != null) {
            updateMaterialCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterialCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$modal.confirm('是否确认删除物料类别编号为"' + row.categoryCode + '"的数据项？').then(function () {
        return delMaterialCategory(row.tableId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    /** 导入按钮操作 */
    handleImport() {
      console.log('操作---------')
      this.upload.title = "物料类别导入";
      this.upload.open = true;
    },
    handleExport() {},
    importTemplate() {
      this.download('/mdm/materialCategory/importTemplate', {
      }, `material_category_template_${new Date().getTime()}.xlsx`)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
